package org.hbbTlias2025.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.hbbTlias2025.utils.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        HttpServletRequest request = (HttpServletRequest) servletRequest;
//        HttpServletResponse response = (HttpServletResponse) servletResponse;

//        获取的请求路径
        String requestURI = request.getRequestURI();
        if (requestURI.contains("/login")){
            log.info("这是token拦截器————登录请求,直接放行");
            return true;
        }

        String token = request.getHeader("token");
        log.info("这是token拦截器————token就是如下的内容{}",token);


        if(token == null || token.isEmpty()){
            log.info("这是token拦截器————token为空,请直接登录");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        try {
            JwtUtil.parseToken(token);
        } catch (Exception e) {
            log.info("这是token拦截器————token非法,请爬爬开");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        log.info("这是token拦截器————令牌合法,请直接登录");
        return true;


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("这是token拦截器————现在是执行一个postHandle,执行完了执行");
    }
}
